package com.ssrs.platform.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ssrs.framework.Config;
import com.ssrs.framework.config.AppDataPath;
import com.ssrs.framework.extend.annotation.ExtendItem;
import com.ssrs.platform.FixedConfigItem;
import com.ssrs.platform.PlatformPlugin;
import com.ssrs.platform.code.ControlType;
import com.ssrs.platform.code.DataType;
import com.ssrs.platform.extend.ConfigService;

import java.io.File;

/**
 * 资源根目录,目录名称以/结束。
 *
 * @author ssrs
 */
@ExtendItem(
        plugin = PlatformPlugin.class,
        extendService = ConfigService.class,
        description = "资源根目录"
)
public class ResourceRoot extends FixedConfigItem {
    public static final String ID = "Content.ResourceRoot";
    public static final String APP_RESOURCE_ROOT = "App.ResourceRoot";
    protected static String lastSetValue;
    protected static String lastGetValue;

    public ResourceRoot() {
        super(ID, DataType.SHORTTEXT, ControlType.TEXT, "配置资源根目录");
    }

    public static String getValue() {
        String resourceRoot = Config.getValue(APP_RESOURCE_ROOT);
        if (StrUtil.isNotEmpty(resourceRoot)) {
            if (lastSetValue == resourceRoot && lastGetValue != null) {
                return lastGetValue;
            } else {
                String path = Config.replacePathHolder(resourceRoot);
                if (!path.endsWith("/")) {
                    path = path + "/";
                }
                lastGetValue = path;
                lastSetValue = resourceRoot;
                return lastGetValue;
            }
        } else {
            resourceRoot = Config.getValue(ID);
            if (lastSetValue == resourceRoot && lastGetValue != null) {
                return lastGetValue;
            } else {
                String path = null;
                if (StrUtil.isEmpty(resourceRoot)) {
                    File f = new File(AppDataPath.getValue());
                    path = f.getParent() + "/resource";
                    path = FileUtil.normalize(path);
                } else {
                    path = Config.replacePathHolder(resourceRoot);
                }
                if (!path.endsWith("/")) {
                    path = path + "/";
                }
                lastSetValue = resourceRoot;
                lastGetValue = path;
                return lastGetValue;
            }
        }
    }
}
